package com.yupi.yuojcodesandbox.controller;

import com.yupi.yuojcodesandbox.JavaNativeCodeSandbox;
import com.yupi.yuojcodesandbox.model.ExcuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExcuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
@Slf4j
public class MainController {
    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    // 定义鉴权请求头和密钥  在请求头里面加一个密钥 调用方和服务器接收的密钥需要一致才进行下一步操作 密钥是不能返回给前端的
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @GetMapping("health")
    public String healthCheck() {
        return "ok";
    }

    //对外暴露接口则在判题服务就可以通过发送http请求这个接口进行代码沙箱的实现
    @PostMapping("executeCode")
    ExcuteCodeResponse excuteCode(@RequestBody ExcuteCodeRequest excuteCodeRequest, HttpServletRequest request,
                                  HttpServletResponse response){
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        //因为header可能为空 所以放到equals方法的参数里面
        if(!AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            return null;
        }
        if(excuteCodeRequest==null){
            throw new RuntimeException("请求参数为空");
        }
        ExcuteCodeResponse excuteCodeResponse = javaNativeCodeSandbox.excuteCode(excuteCodeRequest);
        return excuteCodeResponse;
    }


}
